//require necessary modules
var http = require('http')
  , express = require('express')
  , socketIO = require("socket.io");
 // , log = require('./libs/log');
//initialize our application
var app = express();
//log.use(app);
app.set('port', process.env.PORT || 3000);

var server = http.createServer(app).listen(app.get('port'));
var io = socketIO.listen(server);

// io.set('log level',0);
// io.set('close timeout',20);
function jsonp(data,callback){
  return callback+"("+JSON.stringify(data)+")";
}
var AllUser={};
app.get('/', function(request, response){
  console.log(io.sockets);
  response.json({s:1});
});
app.post('/login',function(req,res){
  req.username='hello';
  res.json({success: true})
});
app.get('/alluser',function(req,res){
  // var users={};
  // var clients = io.sockets.sockets;
  // console.log(clients);
  var users=[];
  for(var i in AllUser){
    var tmp={};
    tmp.username = AllUser[i];
    tmp.id = i;
    users.push(tmp);
  }
  res.jsonp({success: true,users: users})
});
function getcount(id){
  var count = io.sockets.adapter.rooms[id];
  var i = 0;
  console.log(count);
  if(!count){
    i = 0;
  }else{
    i = 0;
    for(var v in count){
      if(count[v]){
        i++;
      }
    }
    //count = i;
  }
  console.log(i);
  return i;
}
// function isjoin(id,clientId){
//   var clients = io.sockets.adapter.rooms[id];
//   if(clients && clients[clientId]){

//   }
// }
app.get('/room/:id',function(req,res){
  
  var count = getcount(req.params.id);
  var data = {counts: count,room: req.params.id};
    console.log(data);
  res.jsonp(data);
  //res.json(jsonp(data,req.query.callback));
});
app.get('/room',function(req,res){
  var result = {};
  var key =0;
  for(var i=1;i<13;i++){
    var room = i+"";
    var count = io.sockets.adapter.rooms[room];
  //console.log(count);
    if(!count){
      key = 0;
    }else{
      var j = 0;
      for(var v in count){
        if(count[v]){
          j++;
        }
      }
      key = j;
    }
    result[room]=key;
  }
  res.jsonp(result);
});
// var redis = require('socket.io-redis');
// io.adapter(redis({ host: '106.186.30.236', port: 6666 }));
// io.set('authorization', function(handshakeData, callback){
//   console.log('Auth: ',handshakeData.query);
//   callback(null, true);
// });
io.sockets.on('connection', function(client){
  //when client sends a join event
  console.log(client.username);
  client.on('joinroom',function(data){
    if(data.username=='请登录'){
      client.emit('nologin',{msg: 'error'});
      return false;
    }
    console.log('username: ',data.username);
    //client
    var count = getcount(data.room);
    if(count>=2){
      //client.leave(client.handshake.query.room);
      console.log('未加入: ',data.room);
      client.emit('full',{msg: "房间已满！"});
    }else{
      console.log('Joinroom: ',data.room);
      client.join(data.room);
    }

  });
  client.on('leaveroom',function(data){
      console.log('username: ',data.username);
      console.log('Leaveroom: ',data.room);
      client.leave(data.room);
  });
  client.on("game",function(data){
    client.broadcast.in(data.room).emit('game',data);
  });
  client.on("hello",function(data){
    console.log(data);
  });
  client.on("joinchats",function(data){
   // client.username=data.username;
    AllUser[client.id]=data.username;
    console.log(data);
    //sockets.emit('refresh',{});
  });
 client.on("message",function(data,fn){
   // client.username=data.username;
   var someone = io.to(data.id);
   if(someone){
     someone.emit('message',data);
     fn({success: true});

   }
    //sockets.emit('refresh',{});
  });
  client.on('disconnect', function(){
      console.log('Disconnect: ',client.id);
      delete AllUser[client.id];
  });


})
